import { login } from "@/api/login";
import {
  getToken,
  setToken,
  removeToken,
  setUsername,
  removeUsername
} from "@/utils/app";

const state = {
  token: "" || getToken(),
  username: ""
};

const getters = {
  username(state) {
    return state.username;
  }
};

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token;
  },
  SET_USERNAME(state, username) {
    state.username = username;
  }
};

const actions = {
  login(context, data) {
    return new Promise((resolve, reject) => {
      login(data)
        .then(res => {
          setToken(res.data.token);
          setUsername(res.data.username);
          context.commit("SET_TOKEN", res.data.token);
          context.commit("SET_USERNAME", res.data.username);
          resolve(res);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  logout(context) {
    return new Promise(resolve => {
      context.commit("SET_TOKEN", "");
      context.commit("SET_USERNAME", "");
      removeToken();
      removeUsername();
      resolve();
    });
  }
};

export default { state, getters, mutations, actions };
